package com.itheima.health.utils;

import com.itheima.health.pojo.Role;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lzx
 * @Date 2020/4/17
 * @Version v1.0
 * @Description 序列化与反序列化工具类
 * 此工具类可以对java对象进行序列化和反序列化,	Redis的key和value都支持二进制安全的字符串
 *      利用工具类将java对象序列化为字节数组, 存入Redis;
 *      取出Redis中的数据, 将字节数组反序列化为java对象, 得到原来的数据
 */
public class SerializeUtils {
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            //序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            //反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 测试
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool();
        Jedis jedis = jedisPool.getResource();

        List<Role> roleList = new ArrayList<>();

        Role role = new Role("zhangsan", "1234");
        System.out.println("role = " + role);
        Role role2 = new Role("lisi", "1234");
        System.out.println("role2 = " + role2);

        roleList.add(role);
        roleList.add(role2);
        System.out.println(roleList);

//        jedis.set("roleList".getBytes(), SerializeUtils.serialize(roleList));
//        byte[] bytes = jedis.get("roleList".getBytes());
//        List unserializeRoleList = (List) SerializeUtils.unserialize(bytes);
//        System.out.println("unserializeRoleList = " + unserializeRoleList);

        /*byte[] serialize = SerializeUtils.serialize(role);
        jedis.set("role".getBytes(), serialize);

        byte[] bytes = jedis.get("role".getBytes());
        Role role1 = (Role) SerializeUtils.unserialize(bytes);
        System.out.println("role1 = " + role1);*/
    }
}
